﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IFRS.Web;
using System.Data;
using IFRS.DataAccess.DAL;
using System.Globalization;
using System.Threading;
using IFRS.Models;
using IFRS_Global;


public partial class IFRS_WIN09_4A : PageBase
{
    #region "---------- Events -----------"
    protected void Page_Load(object sender, EventArgs e)
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
        if (!(Page.IsPostBack || Page.IsCallback))
        {
            this.ViewMenu();
            this.SetErrorMessage();
            this.AddClientScript();
            this.BindDDL();
            this.SetDefaultData();
            if (Request.QueryString["id"] != null)
            {
                this.BindData(Convert.ToInt32(Request.QueryString["id"].ToString()));
            }

        }
        else
        {
            ClientScript.RegisterHiddenField("isPostBack", "1");
        }
    }
    protected void btnSAVE_Click(object sender, EventArgs e)
    {
        bool validatdata = ValidateData();
        if (validatdata)
        {
             SaveData(false);
        }
    }
    protected void btnSAVE_NEW_Click(object sender, EventArgs e)
    {
        bool validatdata = ValidateData();
        if (validatdata)
        {
            SaveData(true);
        }
    }
    protected void btnCANCEL_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/IFRS/WIN09_1S.aspx");
    }
    protected void btnCLEAR_Click(object sender, EventArgs e)
    {
        Response.Redirect(ResolveUrl(Request.Url.AbsoluteUri));
    }
    #endregion
    #region "----- Methods -------"
    private void ViewMenu()
    {
        this.MenuTitleBar = Resources.ifrsMenu.WIN09_4A;
    }

    private void SetErrorMessage()
    {
        btnSAVE.ValidationGroup = "Master";
        btnSAVE_NEW.ValidationGroup = "Master";
        reqTransactionDate.SetRequiredField(lblTransactionDate, txtTransactionDate, btnSAVE);
        reqAccountNo.SetRequiredField(lblAccountNo, txtAccountNo, btnSAVE);
        reqCapitalAmount.SetRequiredField(lblCapitalAmount, txtCapitalAmount, btnSAVE);
        reqCostCenter.SetRequiredField(lblCostCenter, txtCostCenter, btnSAVE);
        reqContractLoanTypeID.SetRequiredField(lblContractLoanTypeID, ddlContractLoanTypeID, btnSAVE);
        reqContractStartDate.SetRequiredField(lblContractStartDate, txtContractStartDate, btnSAVE);
        reqCreditLevelID.SetRequiredField(lblCreditLevelID, ddlCreditLevelID, btnSAVE);
        reqFirstPaymentDate.SetRequiredField(lblFirstPaymentDate, txtFirstPaymentDate, btnSAVE);
        reqLoanObjectiveID.SetRequiredField(lblLoanObjectiveID, txtLoanObjectiveID, btnSAVE);
        reqStartInterestRate.SetRequiredField(lblStartInterestRate, txtStartInterestRate, btnSAVE);
        reqTermAmount.SetRequiredField(lblTermAmount, txtTermAmount, btnSAVE);
        reqUnpaidAmount.SetRequiredField(lblUnpaidAmount, txtUnpaidAmount, btnSAVE);
    }
    private void AddClientScript()
    {
        btnCANCEL.Attributes["OnClick"] = "if(!confirm(\"" + Resources.ifrsResource.ConfirmCancel + "\")) return false;";
        btnCostCenter.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/CostCenter.aspx") + "','700','550');");
        btnCurrencyCodeCD.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/Currency.aspx") + "','700','550');");
        btnGLAccount.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount.aspx") + "','700','550');");
        btnReferenceInterestCD.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/ReferenceInterest.aspx") + "','700','550');");
        btnLoanObjectiveID.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/VmLoanObjective.aspx") + "','700','550');");
        btnCustomer_ID.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/Customer.aspx") + "','700','550');");

        txtCostCenter.AddControl(hidCostCenter.ClientID);
        txtCostCenter.AddControl(txtCostCenter.ClientID);
        txtCostCenter.ControlSearch = txtCostCenter.ClientID;
        txtCostCenter.SearchKey = "VWCostCenter_oCOST_CENTER_CD_oCOST_CENTER_NM";

        txtCurrencyCodeCD.AddControl(hidCurrencyCode.ClientID);
        txtCurrencyCodeCD.AddControl(txtCurrencyCodeCD.ClientID);
        txtCurrencyCodeCD.ControlSearch = txtCurrencyCodeCD.ClientID;
        txtCurrencyCodeCD.SearchKey = "Currency_oCurrencyCode_oCurrencyName";

        txtGLAccountCode.AddControl(hidGLAccountCode.ClientID);
        txtGLAccountCode.AddControl(txtGLAccountCode.ClientID);
        txtGLAccountCode.ControlSearch = txtGLAccountCode.ClientID;
        txtGLAccountCode.SearchKey = "GLAccount_oGLAccountCode_oGLAccountName";

        txtReferenceInterestCD.AddControl(hidReferenceInterestCD.ClientID);
        txtReferenceInterestCD.AddControl(txtReferenceInterestCD.ClientID);
        txtReferenceInterestCD.ControlSearch = txtReferenceInterestCD.ClientID;
        txtReferenceInterestCD.SearchKey = "ReferenceInterest_oReferenceInterestCD_oReferenceInterestNM";

        txtLoanObjectiveID.AddControl(hidLoanObjectiveID.ClientID);
        txtLoanObjectiveID.AddControl(txtLoanObjectiveID.ClientID);
        txtLoanObjectiveID.ControlSearch = txtLoanObjectiveID.ClientID;
        txtLoanObjectiveID.SearchKey = "VmLoanObjective_oCBT_CUST_BUSINESS_TYPE_ID_oCBT_DESC_LEV1";

        txtCustomer_ID.AddControl(hidCustomer_ID.ClientID);
        txtCustomer_ID.AddControl(txtCustomer_ID.ClientID);
        txtCustomer_ID.ControlSearch = txtCustomer_ID.ClientID;
        txtCustomer_ID.SearchKey = "Customer_oCustomerID_oCustomerCode";
    }
    private void BindDDL()
    {
        ddlCustomerPayFreqTimeBase.SetData(DDL_TYPE.PaymentFrequencyTimeBase, "", false, true);
        ddlInterestAdjFreqTimeBase.SetData(DDL_TYPE.PaymentFrequencyTimeBase, "", false, true);
        ddlInterestPayFreqTimeBase.SetData(DDL_TYPE.PaymentFrequencyTimeBase, "", false, true);
        ddlPaymentFreqTimeBase.SetData(DDL_TYPE.PaymentFrequencyTimeBase, "", false, true);
        ddlContractLoanTypeID.SetData(DDL_TYPE.ContractLoanType, "", false, true);
        ddlCreditLevelID.SetData(DDL_TYPE.CreditLevel, "", false, true);
        ddlDayCountMethod.SetData(DDL_TYPE.DayCountMethod, "", false, true);
        ddlInterestTypeID.SetData(DDL_TYPE.InterestType, "", false, true);
        ddlPaymentDate.SetData(DDL_TYPE.PaymentDate, "", false, true);
        ddlPaymentCondition.SetData(DDL_TYPE.PaymentCondition, "", false, true);
    }
    private void SetDefaultData()
    {
        txtCurrencyCodeCD.Text = "THB";
        hidCurrencyCode.Value = "THB";
    }
    private void BindData(int ID)
    {
        var vSPM = new SPR_SORPORMORCREDIT();
        DataTable dtvSPM = vSPM.SEARCH_BYID(ID);
        List<SorPorMorCredit> SPM = new List<SorPorMorCredit>();
        ConvertHelper.ConvertDataTableToObject(dtvSPM, SPM);

        if (dtvSPM.Rows.Count > 0)
        {
            //TextBox
            txtAccountNo.Text = SPM[0].AccountNo;
            txtTransactionDate.Text = DateTime.Now.DateToString();
            txtAdditionalInterest.Text = SPM[0].AdditionalInterest.ToString();
            txtCapitalAmount.Text = SPM[0].CapitalAmount.ToString();
            txtCollateralValue.Text = SPM[0].CollateralValue.ToString();
            txtContractEndDate.Text = DateTime.Now.DateToString();
            txtContractStartDate.Text = DateTime.Now.DateToString();
            txtCostCenter.Text = SPM[0].COST_CENTER_NM;
            txtCurrencyCodeCD.Text = SPM[0].CurrencyCode;
            txtCustomer_ID.Text = SPM[0].CustomerCode;
            txtCustomerPayFreq.Text = SPM[0].CustomerPayFreq.ToString();
            txtEndCalInterestDate.Text = DateTime.Now.DateToString();
            txtFirstPaymentDate.Text = DateTime.Now.DateToString();
            txtGLAccountCode.Text = SPM[0].GLAccountName;
            txtInterestAdjFreq.Text = SPM[0].InterestAdjFreq.ToString();
            txtInterestPayFreq.Text = SPM[0].InterestPayFreq.ToString();
            txtInterestRate.Text = SPM[0].InterestRate.ToString();
            txtLastPaymentDate.Text = DateTime.Now.DateToString();
            txtLoanObjectiveID.Text = SPM[0].CBT_DESC_LEV1;
            txtMisPaymentDate.Text = DateTime.Now.DateToString();
            txtNextPaymentDate.Text = DateTime.Now.DateToString();
            txtNoOfPayment.Text = SPM[0].NoOfPayment.ToString();
            txtPaymentFreq.Text = SPM[0].PaymentFreq.ToString();
            txtReferenceInterestCD.Text = SPM[0].ReferenceInterestNM;
            txtReservedAmount.Text = SPM[0].ReservedAmount.ToString();
            txtStartInterestRate.Text = SPM[0].StartInterestRate.ToString();
            txtStartPaymentDate.Text = DateTime.Now.DateToString();
            txtTermAmount.Text = SPM[0].TermAmount.ToString();
            txtUnpaidAmount.Text = SPM[0].UnpaidAmount.ToString();
            txtUnpaidInterest.Text = SPM[0].UnpaidInterest.ToString();
            //DDL
            ddlContractLoanTypeID.SelectedValue = SPM[0].ContractLoanTypeID.ToString();
            ddlCreditLevelID.SelectedValue = SPM[0].CreditLevelID.ToString();
            ddlCustomerPayFreqTimeBase.SelectedValue = SPM[0].CustomerPayFreqTimeBase;
            ddlDayCountMethod.SelectedValue = SPM[0].DayCountMethodID.ToString();
            ddlInterestAdjFreqTimeBase.SelectedValue = SPM[0].InterestAdjFreqTimeBase;
            ddlInterestPayFreqTimeBase.SelectedValue = SPM[0].InterestPayFreqTimeBase;
            ddlInterestTypeID.SelectedValue = SPM[0].InterestTypeID.ToString();
            ddlPaymentCondition.SelectedValue = SPM[0].PaymentConditionID.ToString();
            ddlPaymentDate.SelectedValue = SPM[0].PaymentDateID.ToString();
            ddlPaymentFreqTimeBase.SelectedValue = SPM[0].PaymentFreqTimeBase;
            //Hid
            hidCostCenter.Value = SPM[0].CostCenter;
            hidCurrencyCode.Value = SPM[0].CurrencyCode;
            hidCustomer_ID.Value = SPM[0].CustomerID.ToString();
            hidGLAccountCode.Value = SPM[0].GLAccount;
            hidLoanObjectiveID.Value = SPM[0].LoanObjectiveID;
            hidReferenceInterestCD.Value = SPM[0].ReferenceInterestCD;

            if (SPM[0].DebtAdjustFlag)
            {
                cbDebtAdjust.Checked = true;
            }
            else
            {
                cbDebtAdjust.Checked = false;
            }

        }
    }
    private bool ValidateData() 
    {
        bool status = true;
        if (!CheckPara(txtPaymentFreq,ddlPaymentFreqTimeBase,lblPaymentFreq,lblPaymentFreqTimeBase))
        {
            status = false;
        }
        else if (!CheckPara(txtInterestPayFreq, ddlInterestPayFreqTimeBase, lblInterestPayFreq, lblInterestPayFreqTimeBase))
        {
            status = false;
        }
        else if (!CheckPara(txtInterestAdjFreq, ddlInterestAdjFreqTimeBase, lblInterestAdjFreq, lblInterestAdjFreqTimeBase))
        {
            status = false;
        }
        else if (!CheckPara(txtCustomerPayFreq, ddlCustomerPayFreqTimeBase, lblCustomerPayFreq, lblCustomerPayFreqTimeBase))
        {
            status = false;
        }
        return status;
    }
    private bool CheckPara(TextBox vtxt, DropDownList vddl, Label lbl_txt, Label lbl_ddl)
    {
        if (vtxt.Text != "" && vddl.SelectedValue.ToString() == "")
        {
            Utility.AlertMessage(Page, Resources.ifrsField.PLEASE_IDENTIFIEND + lbl_ddl.Text);
            return false;
        }
        if (vtxt.Text == "" && vddl.SelectedValue.ToString() != "")
        {
            Utility.AlertMessage(Page, Resources.ifrsField.PLEASE_IDENTIFIEND + lbl_txt.Text);
            return false;
        }
        return true;
    }
    private void SaveData(bool SaveNew)
    {

        try
        {
            SorPorMorCredit vSPM = new SorPorMorCredit();
            vSPM.TransactionDate = txtTransactionDate.Text.StringToDateAllowNull();
            vSPM.AccountNo = txtAccountNo.Text;
            vSPM.AdditionalInterest = txtAdditionalInterest.Text.AsDecimal();
            vSPM.CapitalAmount = txtCapitalAmount.Text.AsDecimal();
            vSPM.CollateralValue = txtCollateralValue.Text.AsDecimal();
            vSPM.ContractEndDate = txtContractEndDate.Text.StringToDateAllowNull();
            vSPM.ContractLoanTypeID = ddlContractLoanTypeID.SelectedValue.AsIntIsnull();
            vSPM.ContractStartDate = txtContractStartDate.Text.StringToDateAllowNull();
            vSPM.CostCenter = hidCostCenter.Value;
            vSPM.CreditLevelID = ddlCreditLevelID.SelectedValue.AsIntIsnull();
            vSPM.CurrencyCode = hidCurrencyCode.Value;
            vSPM.CustomerID = hidCustomer_ID.Value.AsIntIsnull();
            vSPM.CustomerPayFreq = txtCustomerPayFreq.Text.AsDecimal();
            vSPM.CustomerPayFreqTimeBase = ddlCustomerPayFreqTimeBase.SelectedValue.ToString();
            vSPM.DayCountMethodID = ddlDayCountMethod.SelectedValue.AsIntIsnull();
            if (cbDebtAdjust.Checked)
            {
                vSPM.DebtAdjustFlag = true;
            }
            else
            {
                vSPM.DebtAdjustFlag = false;
            }
            vSPM.EndCalInterestDate = txtEndCalInterestDate.Text.StringToDateAllowNull();
            vSPM.FirstPaymentDate = txtFirstPaymentDate.Text.StringToDateAllowNull();
            vSPM.GLAccount = hidGLAccountCode.Value.ToString();
            vSPM.InterestAdjFreq = txtInterestAdjFreq.Text.AsDecimal();
            vSPM.InterestAdjFreqTimeBase = ddlInterestAdjFreqTimeBase.SelectedValue.ToString();
            vSPM.InterestPayFreq = txtInterestPayFreq.Text.AsDecimal();
            vSPM.InterestPayFreqTimeBase = ddlInterestPayFreqTimeBase.SelectedValue.ToString();
            vSPM.InterestRate = txtInterestRate.Text.AsDecimal();
            vSPM.InterestTypeID = ddlInterestTypeID.SelectedValue.AsIntIsnull();
            vSPM.IsConfirmed = true;
            vSPM.LastPaymentDate = txtLastPaymentDate.Text.StringToDateAllowNull();
            vSPM.LoanObjectiveID = hidLoanObjectiveID.Value.ToString();
            vSPM.MisPaymentDate = txtMisPaymentDate.Text.StringToDateAllowNull();
            vSPM.NextPaymentDate = txtNextPaymentDate.Text.StringToDateAllowNull();
            vSPM.NoOfPayment = txtNoOfPayment.Text.AsIntIsnull();
            vSPM.PaymentConditionID = ddlPaymentCondition.SelectedValue.AsIntIsnull();
            vSPM.PaymentDateID = ddlPaymentDate.SelectedValue.AsIntIsnull();
            vSPM.PaymentFreq = txtPaymentFreq.Text.AsDecimal();
            vSPM.PaymentFreqTimeBase = ddlPaymentFreqTimeBase.SelectedValue.ToString();
            vSPM.ReferenceInterestCD = hidReferenceInterestCD.Value.ToString();
            vSPM.ReservedAmount = txtReservedAmount.Text.AsDecimal();
            vSPM.StartInterestRate = txtStartInterestRate.Text.AsDecimal();
            vSPM.StartPaymentDate = txtStartPaymentDate.Text.StringToDateAllowNull();
            vSPM.TermAmount = txtTermAmount.Text.AsDecimal();
            vSPM.UnpaidAmount = txtUnpaidAmount.Text.AsDecimal();
            vSPM.UnpaidInterest = txtUnpaidInterest.Text.AsDecimal();
            vSPM.RP_GSB_PRDCD = "N'SorPorMor";
            vSPM.RP_MAPPING_CD = "N'MANUAL_SorPorMor";
            vSPM.RP_SOURCE_FILE = "N'SorPorMor";
            vSPM.SetStandardField();

            int iID = 0;
            var SPR_SPM = new SPR_SORPORMORCREDIT();
            iID = SPR_SPM.INSERT(vSPM);
            if (iID > 0)
            {

                if (SaveNew)
                {
                    this.JS_Alert(Resources.ifrsResource.SaveData, ResolveUrl("~/IFRS/WIN09_4A.aspx"));
                }
                else
                {
                    this.JS_Alert(Resources.ifrsResource.SaveData, ResolveUrl(string.Format("~/IFRS/WIN09_2E.aspx?&id={0}", iID)));
                }
            }
            else
            {
                if (iID == -1)
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.Duplicate);
                }
                else
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.CanNotSaveData);
                }

            }

        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    #endregion

}